import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  NavBar,
  SearchBar,
  Grid,
  Image,
  Card,
  Empty,
  InfiniteScroll,
  DotLoading,
  Toast
} from 'antd-mobile';
import { getProductPlaceholder } from '../../utils/imageUtils';
import './Search.css';
import { useRequest } from 'ahooks';
import { getProducts } from '../../api/store'


const Search = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [keyword, setKeyword] = useState('');
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);

  // 使用直接调用API的方式，避免useRequest可能的缓存问题
  const fetchData = useCallback(async () => {
    if (!keyword.trim()) {
      return;
    }
    
    setLoading(true);
    try {
      console.log('搜索关键词:', keyword);
      
      // 直接构造参数对象
      const params = { keyword: keyword.trim() };
      console.log('发送请求参数:', params);
      
      // 直接调用API函数
      const response = await getProducts(params);
      console.log('API原始返回结果类型:', typeof response, Array.isArray(response));
      console.log('API原始返回结果:', response);
      
      // 确保filteredProducts是数组
      const safeProducts = Array.isArray(response) ? response : [];
      console.log('处理后的商品数组:', safeProducts);
      
      // 强制设置状态并等待更新
      setProducts(safeProducts);
      
      if (safeProducts.length === 0) {
        Toast.show({
          content: '没有找到相关商品',
          position: 'bottom',
        });
      } else {
        console.log('找到商品数量:', safeProducts.length);
        console.log('第一个商品:', safeProducts[0]);
        Toast.show({
          content: `找到${safeProducts.length}个相关商品`,
          position: 'bottom',
        });
      }
      
      setHasMore(false);
    } catch (error) {
      console.error('Error fetching products:', error);
      setProducts([]); // 出错时设置为空数组
      Toast.show({
        content: '搜索出错，请重试',
        position: 'bottom',
      });
    } finally {
      setLoading(false);
    }
  }, [keyword]);

  // 获取URL参数中的关键词
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const keywordParam = searchParams.get('keyword');
    if (keywordParam) {
      setKeyword(keywordParam);
    }
  }, [location.search]);

  // 搜索商品
  useEffect(() => {
    if (!keyword) return;
    
    console.log('关键词变化，开始搜索:', keyword);
    setProducts([]);
    setPage(1);
    setHasMore(true);
    
    // 使用setTimeout确保状态更新后再执行搜索
    const timer = setTimeout(() => {
      fetchData();
    }, 100);
    
    return () => clearTimeout(timer);
  }, [keyword, fetchData]);

  // 加载更多数据
  const loadMore = async () => {
    if (!products || products.length === 0 || !hasMore) {
      setHasMore(false);
      return;
    }

    setLoading(true);
    // 模拟加载更多数据
    await new Promise(resolve => setTimeout(resolve, 1000));
    setLoading(false);
    setHasMore(false); // 由于我们已经加载了所有匹配的商品，所以不需要加载更多
  };

  // 处理搜索提交
  const handleSearch = (value) => {
    if (!value.trim()) {
      Toast.show({
        content: '请输入搜索关键词',
        position: 'bottom',
      });
      return;
    }
    
    console.log('提交搜索:', value);
    navigate(`/search?keyword=${encodeURIComponent(value.trim())}`);
    setKeyword(value.trim());
  };

  // 返回上一页
  const back = () => {
    navigate(-1);
  };

  // 跳转到商品详情
  const goToProductDetail = (productId) => {
    navigate(`/product/${productId}`);
  };

  // 确保products是数组
  const safeProducts = Array.isArray(products) ? products : [];
  
  // 渲染前检查数据
  console.log('渲染前的商品数组:', safeProducts);

  return (
    <div className="search-page">
      <NavBar onBack={back}>搜索商品</NavBar>

      <div className="search-bar-container">
        <SearchBar
          placeholder='输入关键词搜索'
          value={keyword}
          onChange={setKeyword}
          onSearch={handleSearch}
          showCancelButton
        />
      </div>

      <div className="search-result">
        {safeProducts.length === 0 && !loading ? (
          <Empty description="暂无相关商品" />
        ) : (
          <Grid columns={2} gap={8}>
            {safeProducts.map(product => (
              <Grid.Item key={product.id}>
                <Card
                  className="product-card"
                  onClick={() => goToProductDetail(product.id)}
                >
                  <Image src={product.images?.[0] || product.image || getProductPlaceholder(product.name)} fit='cover' />
                  <div className="product-info">
                    <div className="product-name">{product.name}</div>
                    <div className="product-price">
                      <span className="price">¥{product.price.toFixed(2)}</span>
                      {product.originalPrice && (
                        <span className="original-price">¥{product.originalPrice.toFixed(2)}</span>
                      )}
                    </div>
                    <div className="product-sales">已售 {product.sales}</div>
                  </div>
                </Card>
              </Grid.Item>
            ))}
          </Grid>
        )}

        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
          {hasMore ? (
            <div className="loading-more">
              <span>加载中</span>
              <DotLoading />
            </div>
          ) : (
            safeProducts.length > 0 && <div className="loading-complete">没有更多了</div>
          )}
        </InfiniteScroll>
      </div>
    </div>
  );
};

export default Search;